import { Controller, ForbiddenException, Get, NotFoundException, Param, Post, Res, UploadedFiles, UseInterceptors } from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { ApiOperation } from '@nestjs/swagger';
import { createWriteStream, existsSync } from 'fs';
import { makeDir, readdir, taskDir, taskFile, unlinkDir, writefile } from 'src/libs/path';
import { PrismaService } from 'src/prisma/prisma.service';
import * as archiver from "archiver"
import { Response } from "express"
import { join } from 'path';
@Controller('work')
export class WorkController {
    constructor(
        private readonly prismaService: PrismaService
    ) { }

    @Get(":id/download/:name")
    @ApiOperation({ summary: "下载作业" })
    async download(
        @Param("id") taskid: string,
        @Res() res: Response
    ) {
        const id = Number(taskid);
        if (isNaN(id)) throw new ForbiddenException()
        const work = await this.prismaService.work.findFirst({
            where: {
                id
            },
            include: {
                media: {
                    include: {
                        student: true
                    }
                }
            }
        })
        if (!work) throw new NotFoundException();
        const archive = archiver('zip', { zlib: { level: 9 } });
        archive.pipe(res);

        for (const media of work.media) {
            const path = taskDir(media.id);
            if (!existsSync(path)) {
                console.log("-------------------")
                console.log("找不到路径", path)
                console.log(media.student.name)
                console.log("-------------------")
                continue;
            }
            archive.directory(media.student.name, false)
            const names = await readdir(path);
            for (const name of names) {
                archive.file(join(path, name), { name: `${media.student.name}/${name}` })
            }
        }
        archive.finalize();
    }


    @Post(":id/upload")
    @ApiOperation({ summary: "上传作业" })
    @UseInterceptors(FilesInterceptor('file', 10),)
    async uploadWork(
        @Param("id") taskid: string,
        @UploadedFiles() files: Express.Multer.File[]
    ) {
        const id = Number(taskid);
        if (isNaN(id)) throw new ForbiddenException()
        const media = await this.prismaService.media.findFirst({
            where: {
                id
            }
        })
        if (!media) throw new NotFoundException()
        const dir = taskDir(media.id)
        await unlinkDir(dir)
        await makeDir(dir);
        for (const file of files) {
            file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf8');
            const path = taskFile(media.id, file.originalname)
            await writefile(path, file.buffer);
        }
    }
}
